package com.study.test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class TEST61433774 {
    public static byte[] sendMsg(){
        StringBuffer temp = new StringBuffer();
        temp.append("GET http://www.baidu.com HTTP\\1.1\r\n");
//        temp.append("Host: 127.0.0.1:8080\r\n");
        temp.append("Connection: keep-alive\r\n");
        temp.append("Cache-Control: max-age=0\r\n");
        temp.append("User-Agent: Mozilla\\5.0 (Windows NT 5.1) AppleWebKit\\536.11 (KHTML, like Gecko) Chrome\\20.0.1132.47 Safari\\536.11\r\n");
        temp.append("Accept: text\\html,application\\xhtml+xml,application\\xml;q=0.9,*\\*;q=0.8\r\n");
        temp.append("Accept-Encoding: gzip,deflate,sdch\r\n");
        temp.append("Accept-Language: zh-CN,zh;q=0.8\r\n");
        temp.append("Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3\r\n");
        temp.append("\r\n");
        return temp.toString().getBytes();
    }

    public static void main(String[] args) throws Exception {

        SocketChannel socketChannel= SocketChannel
                .open(new InetSocketAddress("www.baidu.com",80));
        socketChannel.configureBlocking(false);
        Charset charset = Charset.forName("GBK");
        while(!socketChannel.finishConnect()){
            Thread.sleep(100);
        }
        socketChannel.write(ByteBuffer.wrap(sendMsg()));
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int read = 0;
        boolean readed = false;
        while((read = socketChannel.read(byteBuffer))!=-1){
            if(read==0&&readed){
                break;
            }else if(read==0){
                continue;
            }
            byteBuffer.flip();
            readed = true;
            String result = charset.decode(byteBuffer).toString();
//            System.out.println("*****************");
//            System.out.println(result);
            String[] split = result.split("\r\n");
            for (String s : split) {
                if(s.contains("Server")){
                    result = s;
                    break;
                }
            }
            System.out.println("我的QQ号：61433774，我的解析到百度服务器server类型是：" + result);
//            System.out.println("*****************");

            byteBuffer.clear();
        }


    }
}
